package com.sicheng.lc.周赛.分类.思维.配对抵消;

import java.util.HashMap;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/7/5 10:17
 */
public class 连接两字母单词得到的最长回文串 {
    //https://leetcode.cn/problems/longest-palindrome-by-concatenating-two-letter-words/
    public int longestPalindrome(String[] words) {

        HashMap<String, Integer> set = new HashMap<>();
        int res = 0;
        int same = 0;
        StringBuilder t = new StringBuilder(2);
        for (String word : words) {
            if (word.charAt(0) == word.charAt(1)) {
                int x = set.getOrDefault(word, 0);
                if (x == 0) {
                    set.put(word, 1);
                    same++;
                } else {
                    set.put(word, x - 1);
                    res += 4;
                    same--;
                }
            } else {
                t.delete(0, t.length());
                String s = t.append(word).reverse().toString();
                int x = set.getOrDefault(s, 0);
                if (x > 0) {
                    set.put(s, x - 1);
                    res += 4;
                } else {
                    set.put(word, set.getOrDefault(word, 0) + 1);
                }
            }
        }
        return res + (same > 0 ? 2 : 0);
    }

    public static void main(String[] args) {
        连接两字母单词得到的最长回文串 s = new 连接两字母单词得到的最长回文串();
        String[] ss = {"qo", "fo", "fq", "qf", "fo", "ff", "qq", "qf", "of", "of", "oo", "of", "of", "qf", "qf", "of"};
        System.out.println(s.longestPalindrome(ss));
    }
}
